package com.example;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: wyp
 * @Date: 2021/9/9 15:11
 * 自旋锁
 */
public class SpinLockDemo {
    public static void main(String[] args) {
        Spin spin = new Spin();

        new Thread(() -> {
            spin.lock();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spin.unlock();
        }, "A").start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            spin.lock();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spin.unlock();
        }, "B").start();
    }
}

class Spin {
    AtomicReference<Thread> lock = new AtomicReference<>();

    public void lock() {
        int i = 0;
        while (!lock.compareAndSet(null, Thread.currentThread())){
            i++;
        }
        System.out.println(Thread.currentThread().getName()+"自旋了："+i+"次");
        System.out.println(Thread.currentThread().getName() + "锁定！");
    }

    public void unlock() {
        lock.compareAndSet(Thread.currentThread(), null);
        System.out.println(Thread.currentThread().getName() + "解锁！");
    }
}